<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 角色列表卡片 -->

    <el-card class="box-card">
      <el-button type="primary" @click="addRoleVisible = true"
        >添加角色</el-button
      >
      <!-- 角色表格 -->
      <template>
        <el-table :data="RoleList" border style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                v-for="(item, index) in scope.row.children"
                :key="item.id"
                :class="['Item1', index === 0 ? 'item1Top' : '']"
                class="item1"
              >
                <el-col :span="5">
                  <el-tag closable @close="delTag(scope.row, item.id)">{{
                    item.authName
                  }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <el-row
                    v-for="(newitem, index) in item.children"
                    :key="newitem.key"
                    :class="[index !== 0 ? 'item2Top' : '']"
                  >
                    <el-col :span="4">
                      <el-tag
                        closable
                        type="success"
                        @close="delTag(scope.row, newitem.id)"
                        >{{ newitem.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="20" class="item3">
                      <el-tag
                        type="warning"
                        closable
                        @close="delTag(scope.row, lastitem.id)"
                        v-for="lastitem in newitem.children"
                        :key="lastitem.id"
                        >{{ lastitem.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#" width="60"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="技术负责人">
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-tooltip content="修改角色" placement="top" :enterable="false">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editUser(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="分配权限" placement="top" :enterable="false">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-share"
                  @click="editRight(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除角色" placement="top" :enterable="false">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delUser(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 添加用户 -->
      <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="30%">
        <el-form label-position="left" label-width="80px" :model="addRoleForm">
          <el-form-item label="角色名称">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="addnewRole"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="editRightVisible"
        width="30%"
        @close="resetRight"
      >
        <el-tree
          ref="TreeRef"
          :data="RightsList"
          show-checkbox
          node-key="id"
          
          :default-checked-keys="rightKeys"
          :props="defaultProps"
          :default-expand-all="true"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRightVisible = false">取 消</el-button>
          <el-button type="primary" @click="Rights">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改角色 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editRoleVisible"
        width="30%"
        @close="closeRoleForm"
      >
        <el-form
          label-position="left"
          label-width="80px"
          :model="editRoleForm"
          ref="editRoleFormRef"
        >
          <el-form-item label="角色名称">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pagenum"
        :page-sizes="[2, 3, 5, 6]"
        :default-checked-keys="rightKeys"
        :page-size="pagination.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import newList from "@/until/dataPagination.js";
export default {
  data() {
    return {
      editRoleVisible: false,
      RoleList: [],
      RightsList: [],
      rightKeys: [],
      pagination: {
        total: 10,
        pagenum: 1,
        pagesize: 2,
      },
      defaultProps: {
        children: "children",
        label: "authName",
      },
      currentRoleid: null,
      addRoleVisible: false,
      // 分配权限框
      editRightVisible: false,
      editRoleForm: {
        roleName: "", //角色名称
        roleDesc: "", //角色描述
        id: null,
      },
      addRoleForm:{
        roleName: "", //角色名称
        roleDesc: "", //角色描述
      }
    };
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      const { data: res } = await this.$axios.get("roles");
      this.pagination.total = res.data.length;
      this.RoleList = newList(res.data, this.pagination);
      console.log(this.RoleList);
    },

    // 页码改变触发
    handleSizeChange(newpagesize) {
      this.pagination.pagesize = newpagesize;
      this.getRoleList();
    },
    //页数改变触发
    handleCurrentChange(newpagenum) {
      this.pagination.pagenum = newpagenum;
      this.getRoleList();
    },

    // 发送请求分配权限
    async Rights() {
      const keys = [
        ...this.$refs.TreeRef.getCheckedKeys(),
        ...this.$refs.TreeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);
      const { data: res } = await this.$axios.post(
        "roles/" + this.currentRoleid + "/rights",
        {
          rids: keys.join(","),
        }
      );
      if (res.meta.status == 200) {
        this.$message.success("修改用户权限成功");
        this.getRoleList();
      }
      this.editRightVisible = false;
    },

    //点击分配权限
    async editRight(role) {
      this.currentRoleid = role.id;
      this.editRightVisible = true;
      const { data: res } = await this.$axios.get("rights/tree");
      console.log(res.data);
      this.RightsList = res.data;
      this.newKeys(role, this.rightKeys);

      // console.log(this.rightKeys);
    },

    // 重置权限选择框
    resetRight() {
      this.rightKeys = [];
    },

    //重置修改角色信息表单
    closeRoleForm() {
      this.$refs.editRoleFormRef.resetFields();
    },


    // 增加新用户
    async addnewRole(){
      const {data:res} = await this.$axios.post("roles",{
        roleName:this.addRoleForm.roleName,
        roleDesc:this.addRoleForm.roleDesc
      })
      if(res.meta.status == 201){
        this.$message.success("新增用户成功")
        this.getRoleList()
      }
      this.addRoleVisible = false;
    },

    // 点击确定修改角色信息
    async editRoleInfo() {
      const { data: res } = await this.$axios.put(
        "roles/" + this.editRoleForm.id,
        {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc,
        }
      );
      console.log(res);
      if (res.meta.status == 200) {
        this.getRoleList();
        this.$message.success("修改角色信息成功");
        this.editRoleVisible = false;
      }
    },

    editUser(row) {
      // console.log(row);
      this.editRoleForm.id = row.id;
      this.editRoleForm.roleName = row.roleName;
      this.editRoleForm.roleDesc = row.roleDesc;
      this.editRoleVisible = true;
    },

    newKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => {
        this.newKeys(item, arr);
      });
    },

    //点击标签删除角色权限
    async delTag(role, rightid) {
      console.log(role.id);
      const flag = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(flag);
      if (flag == "confirm") {
        const { data: res } = await this.$axios.delete(
          "roles/" + role.id + "/rights/" + rightid
        );

        if (res.meta.status === 200) {
          this.$message.success("删除该用户权限成功");
          role.children = res.data;
        }
      }
      // console.log(id)
    },

    // 删除角色
    async delUser(row) {
      const flag = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (flag == "confirm") {
        const { data: res } = await this.$axios.delete("roles/" + row.id);
        if (res.meta.status == 200) {
          this.$message.success("删除角色成功");
          this.getRoleList();
        }
      }
    },
  },
};
</script>

<style scope>
.Item1 {
  border-bottom: 1px solid #ccc;
}

.item1Top {
  padding-top: 15px;
  border-top: 1px solid #ccc;
}

.item2Top {
  padding-top: 10px;
  border-top: 1px solid #ccc;
}

.item3 .el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.item1 {
  display: flex;
  align-items: center;
}
</style>
